'use strict'
const Node = require('../module/node')
const SUN = require('../base/sun')
let nodeSerconfig = SUN.serConfig.nodeSerconfig


//会话管理类(用子节点连接管理类)
class NodeMgr {
    constructor() {
        this.nodes = {} //保存nodeId对应的node
        this.sceneNodes = [] //用户场景节点数组
        this.chatNode = null //聊天节点
        this.multiNode = null //多人场景节点
        this.curId = 1
    }

    create(socket) {
        let self = this,
            node = new Node(this.curId, socket)
        this.nodes[this.curId] = node
        this.curId += 1
        node.on('close', function(data) {
            self.delNodeByNid(data.id)
        })
        return node
    }

    getNodeByNid(nId) {
        return this.nodes[nId]
    }

    bind(nId, name, type) {
        console.info(name + '子节点绑定')
        let self = this
        this.nodes[nId].name = name
        this.nodes[nId].type = type
        switch (type) {
            case 1:
                if (!this.sceneNodes.find((id) => id === nId)) {
                    self.sceneNodes.push(nId)
                }
                break
            case 2:
                this.chatNode = this.nodes[nId]
                break
            case 3:
                this.multiNode = this.nodes[nId]
                break
            default:
        }
    }

    delNode(node) {
        let nId = node.id
        this.delNodeByNid(nId)
    }

    delNodeByNid(nId) {
        let node = this.nodes[nId]
        let nodeType = node.type
        switch (nodeType) {
            case 1:
                let findIndex = this.sceneNodes.find(function(id) {
                    return id === node.id
                })
                this.sceneNodes.splice(findIndex, 1)
                break
            default:
        }
        SUN.emit('closeNode', node.id)
        delete this.nodes[nId]
    }

    //获得随机节点
    getRandomNode() {
        let index = Math.floor(Math.random() * this.sceneNodes.length)
        let id = this.sceneNodes[index]
        return this.nodes[id]
    }
}
let nodeMgr = new NodeMgr()
module.exports = nodeMgr
